<template>
  <div class="knowledge-management">
    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增知识
        </el-button>
        <el-button @click="handleBatchDelete" :disabled="selectedItems.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
      <div class="action-right">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索知识库..."
          style="width: 300px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="分类:">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="产品咨询" value="product" />
            <el-option label="技术支持" value="technical" />
            <el-option label="订单相关" value="order" />
            <el-option label="售后服务" value="service" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="searchForm.isEnabled" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 知识库表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="question" label="问题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryLabel(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ scope.row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isEnabled"
              @change="handleToggleStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button type="text" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <span>共{{ total }} 条数据</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="prev, pager, next, sizes"
        @current-change="loadData"
        @size-change="loadData"
      />
      <div class="page-size">
        <span>{{ pageSize }} 条/页</span>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑知识' : '新增知识'"
      width="60%"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入知识标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="产品咨询" value="product" />
                <el-option label="技术支持" value="technical" />
                <el-option label="订单相关" value="order" />
                <el-option label="售后服务" value="service" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="问题" prop="question">
          <el-input
            v-model="form.question"
            type="textarea"
            :rows="3"
            placeholder="请输入问题描述"
          />
        </el-form-item>
        
        <el-form-item label="答案" prop="answer">
          <el-input
            v-model="form.answer"
            type="textarea"
            :rows="5"
            placeholder="请输入答案内容"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-input-number
                v-model="form.priority"
                :min="0"
                :max="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="匹配阈值" prop="matchThreshold">
              <el-input-number
                v-model="form.matchThreshold"
                :min="0"
                :max="1"
                :step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签，用逗号分隔" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="相关链接" prop="relatedLinks">
          <el-input v-model="form.relatedLinks" placeholder="请输入相关链接" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="知识详情" width="50%">
      <div v-if="viewData" class="knowledge-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题">{{ viewData.title }}</el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag :type="getCategoryType(viewData.category)">
              {{ getCategoryLabel(viewData.category) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="问题" :span="2">{{ viewData.question }}</el-descriptions-item>
          <el-descriptions-item label="答案" :span="2">
            <div class="answer-content" v-html="viewData.answer"></div>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">{{ viewData.priority }}</el-descriptions-item>
          <el-descriptions-item label="匹配阈值">{{ viewData.matchThreshold }}</el-descriptions-item>
          <el-descriptions-item label="标签" :span="2">{{ viewData.tags }}</el-descriptions-item>
          <el-descriptions-item label="相关链接" :span="2">
            <a v-if="viewData.relatedLinks" :href="viewData.relatedLinks" target="_blank">
              {{ viewData.relatedLinks }}
            </a>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import { AICustomerService } from '@/services/aiCustomerService'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const tableData = ref<any[]>([])
const selectedItems = ref<any[]>([])
const viewData = ref<any>(null)
const formRef = ref()

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  keyword: '',
  category: '',
  isEnabled: undefined
})

// 表单数据
const form = ref({
  knowledgeId: 0,
  title: '',
  question: '',
  answer: '',
  category: '',
  tags: '',
  priority: 5,
  matchThreshold: 0.8,
  relatedLinks: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入知识标题', trigger: 'blur' }
  ],
  question: [
    { required: true, message: '请输入问题描述', trigger: 'blur' }
  ],
  answer: [
    { required: true, message: '请输入答案内容', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 初始化
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      keyword: searchForm.value.keyword || undefined,
      category: searchForm.value.category || undefined,
      isEnabled: searchForm.value.isEnabled,
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response = await AICustomerService.queryKnowledge(params)
    
    if (response.code === 200) {
      tableData.value = response.data?.data || []
      total.value = response.data?.total || 0
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    keyword: '',
    category: '',
    isEnabled: undefined
  }
  currentPage.value = 1
  loadData()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  viewData.value = row
  viewDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除知识"${row.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await AICustomerService.deleteKnowledge(row.knowledgeId)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.value.length} 条知识吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 批量删除逻辑（需要后端支持）
    for (const item of selectedItems.value) {
      await AICustomerService.deleteKnowledge(item.knowledgeId)
    }
    
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  try {
    const response = await AICustomerService.toggleKnowledgeStatus(
      row.knowledgeId,
      row.isEnabled
    )
    
    if (response.code === 200) {
      ElMessage.success(`已${row.isEnabled ? '启用' : '禁用'}`)
    } else {
      ElMessage.error(response.msg || '操作失败')
      // 恢复状态
      row.isEnabled = !row.isEnabled
    }
  } catch (error) {
    ElMessage.error('操作失败')
    // 恢复状态
    row.isEnabled = !row.isEnabled
  }
}

// 表格选择
const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let response
    if (isEdit.value) {
      response = await AICustomerService.updateKnowledge(form.value)
    } else {
      response = await AICustomerService.createKnowledge(form.value)
    }
    
    if (response.code === 200) {
      ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.msg || `${isEdit.value ? '更新' : '创建'}失败`)
    }
  } catch (error) {
    ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    knowledgeId: 0,
    title: '',
    question: '',
    answer: '',
    category: '',
    tags: '',
    priority: 5,
    matchThreshold: 0.8,
    relatedLinks: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 获取分类标签类型
const getCategoryType = (category: string) => {
  const types: Record<string, string> = {
    product: 'primary',
    technical: 'success',
    order: 'warning',
    service: 'info',
    other: ''
  }
  return types[category] || ''
}

// 获取分类标签
const getCategoryLabel = (category: string) => {
  const labels: Record<string, string> = {
    product: '产品咨询',
    technical: '技术支持',
    order: '订单相关',
    service: '售后服务',
    other: '其他'
  }
  return labels[category] || category
}

// 获取优先级类型
const getPriorityType = (priority: number) => {
  if (priority >= 8) return 'danger'
  if (priority >= 5) return 'warning'
  return 'info'
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped>
.knowledge-management {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.action-left {
  display: flex;
  gap: 10px;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.page-size {
  color: #909399;
}

.knowledge-detail {
  padding: 20px 0;
}

.answer-content {
  line-height: 1.6;
  word-wrap: break-word;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>
